package com.whiteape.book.utils;

import java.net.URL;
import java.util.Map;

public class URLUtils {
    public static String getAbsolutePath(String baseUrl, String currentUrl) {
        if (currentUrl.startsWith("http")) {
            return currentUrl;
        }
        try {
            URL baseURL = new URL(baseUrl);
            URL absoluteURL = new URL(baseURL, currentUrl);
            return absoluteURL.toString();
        } catch (Exception e) {
            return "";
        }
    }

    public static String getUrlWithParams(String url, Map<String, String> params) {
        if (!url.endsWith("?")) {
            url = url + "?";
        }
        StringBuilder sb = new StringBuilder(url);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&")
            ;

        }
        return sb.substring(0, sb.length() - 1);

    }

    public static boolean isUrlsEqual(String url1, String url2) {
        if (!url1.endsWith("/")) {
            url1 = url1 + "/";
        }

        if (!url2.endsWith("/")) {
            url2 = url2 + "/";
        }

        return url1.equals(url2);
    }

    public static String getBaseUrl(String urlStr) {
        try {
            URL url = new URL(urlStr);
            return url.getProtocol() + "://" + url.getHost() + "/";
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
